package com.smart.buss.ctrl;

import com.smart.buss.dao.BussTaskMapper;
import com.smart.buss.service.BussTaskLogService;
import com.smart.buss.service.BussTaskService;
import com.smart.buss.vo.BussTask;
import com.smart.buss.vo.BussTaskLog;
import com.smart.buss.vo.BussUser;
import com.smart.buss.vo.resp.BussTaskResp;
import com.smart.primary.common.common.BaseCtrl;
import com.smart.primary.common.common.Constants;
import com.smart.primary.common.util.*;
import com.smart.primary.sys.vo.User;
import com.smart.primary.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/buss/task")
public class BussTaskController extends BaseCtrl {
	private final static Logger logger= Logger.getLogger(BussTaskController.class);

	@Autowired
	private BussTaskService bussTaskService;
	@Autowired
	private BussTaskLogService bussTaskLogService;

	@Resource
	private BussTaskMapper bussTaskMapper;

	@ResponseBody
	@Transactional
	@RequestMapping
	public AjaxResult getList(BussTask entity) throws Exception{
		//设置置顶
		if(StringUtils.isNotBlank(entity.getField())){
			bussTaskService.stick(entity);
		}

		//设置上下架
		if(StringUtils.isNotBlank(entity.getOrder())){
			BussTask task=new BussTask();
			task.setId(entity.getOrder());
			task=bussTaskService.queryObject(task);
			if(task!=null && task.getIsclose()==1 && task.getTaskStatus()==0){
				task.setIsclose(0);
				bussTaskService.update(task);
			}
			bussTaskService.stop(entity);
		}
		List<BussTask> list=new ArrayList<>();
		if(entity.getIsclose()!=null && entity.getIsclose()==1 && StringUtils.isNotBlank(entity.getCode())){
			list=bussTaskService.queryCloseListByPage(entity);
		}else {
			list=bussTaskService.queryListByPage(entity);
		}




		String path= PropertiesUtil.getString("res.web.url");
		for(BussTask user:list ){
			if(StringUtils.isNotBlank(user.getImgIcon())){
				user.setImgIcon(path+user.getImgIcon());
			}
			if(StringUtils.isNotBlank(user.getImgShili())){
				String[] arr=user.getImgShili().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				user.setImgShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}
			if(StringUtils.isNotBlank(user.getImgUploadShili())){
				String[] arr=user.getImgUploadShili().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				user.setImgUploadShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}
		}
		return getResult(entity, list);
	}




	@ResponseBody
	@Transactional
	@RequestMapping("/info")
	public AjaxResult info() throws Exception{

		closeTask();

		int a=0;
		int b=0;
		int c=0;
		int d=0;
		BussTask entity=new BussTask();
		entity.setTaskStatus(1);
		a=bussTaskService.queryCount(entity);
		BussTask entity1=new BussTask();
		entity1.setTaskStatus(0);
		b=bussTaskService.queryCount(entity1);

		BussTask entity2=new BussTask();
		entity2.setIsclose(1);
		entity2.setCode("duibi");
		List<BussTask> list=bussTaskService.queryCloseListByPage(entity2);

		entity2.setCode("wancheng");
		List<BussTask> list2=bussTaskService.queryCloseListByPage(entity2);
		Map m=new HashMap();
		m.put("a",a);
		m.put("b",b);
		m.put("c",list.size());
		m.put("d",list2.size());

		return AjaxResult.success(m);
	}

	@ResponseBody
	@Transactional
	@RequestMapping("/mytask")
	public AjaxResult my(BussTask entity) throws Exception{
		User user1 = SessionUtil.getUser(request,response);

		List<BussTask> list=new ArrayList<>();

		if (user1 == null || StringUtil.isBlank(user1.getQudao())) {
			return getResult(entity, list);
		}
		entity.setQudao(user1.getQudao());
		if(entity.getIsclose()!=null && entity.getIsclose()==1 && StringUtils.isNotBlank(entity.getCode())){
			list=bussTaskService.queryCloseListByPage(entity);
		}else {
			list=bussTaskService.queryListByPage(entity);
		}

		String path= PropertiesUtil.getString("res.web.url");
		for(BussTask user:list ){
			if(StringUtils.isNotBlank(user.getImgIcon())){
				user.setImgIcon(path+user.getImgIcon());
			}
			if(StringUtils.isNotBlank(user.getImgShili())){
				String[] arr=user.getImgShili().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				user.setImgShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}
			if(StringUtils.isNotBlank(user.getImgUploadShili())){
				String[] arr=user.getImgUploadShili().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				user.setImgUploadShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}
		}
		return getResult(entity, list);
	}


	@ResponseBody
	@Transactional
	@RequestMapping("/myinfo")
	public AjaxResult myinfo() throws Exception{

		closeTask();



		int a=0;
		int b=0;
		int c=0;
		int d=0;



		User user = SessionUtil.getUser(request,response);
		if (user == null || StringUtil.isBlank(user.getQudao())) {
			Map m=new HashMap();
			m.put("a",0);
			m.put("b",0);
			m.put("c",0);
			m.put("d",0);
			return AjaxResult.success(m);
		}

		BussTask entity=new BussTask();
		entity.setQudao(user.getQudao());
		entity.setTaskStatus(1);
		a=bussTaskService.queryCount(entity);
		BussTask entity1=new BussTask();
		entity1.setTaskStatus(0);
		entity1.setQudao(user.getQudao());
		b=bussTaskService.queryCount(entity1);

		BussTask entity2=new BussTask();
		entity2.setIsclose(1);
		entity2.setCode("duibi");
		entity2.setQudao(user.getQudao());
		List<BussTask> list=bussTaskService.queryCloseListByPage(entity2);

		entity2.setCode("wancheng");
		List<BussTask> list2=bussTaskService.queryCloseListByPage(entity2);
		Map m=new HashMap();
		m.put("a",a);
		m.put("b",b);
		m.put("c",list.size());
		m.put("d",list2.size());

		return AjaxResult.success(m);
	}

	//http://192.168.0.6:8080/task/buss/task/page?userId=12345678910
	@ResponseBody
	@RequestMapping("/page")
	public AjaxResult listpage(BussTask entity) throws Exception{



		closeTask();
		entity.setTaskStatus(1);
		entity.setIsclose(0);
		entity.setQudao(getqudao());
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		List<BussTaskResp> resp=bussTaskMapper.taskQueryListByPage(entity);


		String path= PropertiesUtil.getString("res.web.url");
		for(BussTaskResp user:resp ){
			if(StringUtils.isNotBlank(user.getImgIcon())){
				user.setImgIcon(path+user.getImgIcon());
			}

			if(StringUtils.isNotBlank(user.getImgShili())){
				String[] arr=user.getImgShili().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				user.setImgShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}

			if(StringUtils.isNotBlank(user.getImgUploadShili())){
				String[] arr=user.getImgUploadShili().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				user.setImgUploadShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}

			if(StringUtils.isNotBlank(entity.getUserId())){
				BussTaskLog log=new BussTaskLog();
				log.setUserId(entity.getUserId());
				log.setTaskId(user.getId());
				log.setCheckStatus(-1);
				BussTaskLog qlog=bussTaskLogService.queryObject(log);
				user.setTaskStatus(0);
				if(qlog!=null ){
					Integer sout=(int)(System.currentTimeMillis()/1000-qlog.getUpdateDate().getTime()/1000);
					Integer aa=user.getTimeOut()-sout;
					if(aa>0){
						user.setSout(aa);
						user.setTaskStatus(1);
					}
				}

				// 审核中的任务
				user.setShenheStatus(0);
				log.setCheckStatus(0);
				List<BussTaskLog> shenhe=bussTaskLogService.queryList(log);
				if(shenhe !=null && shenhe.size()>0){
					user.setShenheStatus(1);
				}

			}
		}
		return getResult(entity, resp);
	}

	@ResponseBody
	@RequestMapping("/list")
	public List<BussTask> list(BussTask entity) throws Exception{
		return bussTaskService.queryList(entity);
	}
	@ResponseBody
	@RequestMapping("/getOne")
	public AjaxResult getOne(BussTask entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		logger.info("/task/getOne中获取到的主键："+phone);
		if(StringUtils.isBlank(entity.getId()) || StringUtils.isBlank(entity.getUserId())){
			return AjaxResult.failure("参数错误");
		}
		BussTask task=bussTaskService.queryObject(entity);

		BussTaskLog log=new BussTaskLog();
		log.setTaskId(entity.getId());
		log.setUserId(entity.getUserId());
		log.setCheckStatus(-1);
		BussTaskLog qlog=bussTaskLogService.queryObject(log);

		if(task!=null){
			task.setTaskStatus(0);
			String path= PropertiesUtil.getString("res.web.url");
			if(StringUtils.isNotBlank(task.getImgIcon())){
				task.setImgIcon(path+task.getImgIcon());
			}

			if(StringUtils.isNotBlank(task.getImgShili())){
				String[] arr=task.getImgShili().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				task.setImgShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}
			if(StringUtils.isNotBlank(task.getImgUploadShili())){
				String[] arr=task.getImgUploadShili().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				task.setImgUploadShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}
		}

		if(qlog!=null ){

			Integer sout=(int)(System.currentTimeMillis()/1000-qlog.getUpdateDate().getTime()/1000);
			Integer aa=task.getTimeOut()-sout;
			if(aa>0){
				task.setSout(aa);
				task.setTaskStatus(1);
			}

		}

			return AjaxResult.success(task);

	}

	@ResponseBody
	@RequestMapping("/save")
	public AjaxResult save(BussTask entity) throws Exception{
		if(StringUtils.isNotBlank(entity.getImgShili())){
			entity.setImgShili(entity.getImgShili().substring(0,entity.getImgShili().length()-1));
		}
		if(StringUtils.isNotBlank(entity.getQudao())){
			entity.setQudao(entity.getQudao().replace("undefined",""));
		}
		if(StringUtils.isNotBlank(entity.getImgUploadShili())){
			entity.setImgUploadShili(entity.getImgUploadShili().substring(0,entity.getImgUploadShili().length()-1));
		}
		if(StringUtils.isBlank(entity.getId())){
			entity.setId(Util.getUUID());
			bussTaskService.insert(entity);
			return AjaxResult.updateSuccess();
		}else {
			if(entity.getTaskStatus()!=null && entity.getTaskStatus()==1){
				entity.setIsclose(0);
			}
			bussTaskService.update(entity);
			return AjaxResult.saveSuccess();
		}
	}
	@ResponseBody
	@RequestMapping("/del")
	public AjaxResult del(String id) throws Exception{
		bussTaskService.delete(id);
		return AjaxResult.deleteSuccess();
	}
	@ResponseBody
	@RequestMapping("/hide")
	public AjaxResult hide(BussTask entity) throws Exception{
		BussTask query=bussTaskService.queryObject(entity);
		if(query==null){
			return AjaxResult.failure();
		}
		if(query.getIshide() !=null ){
			if( query.getIshide()==1){
				query.setIshide(0);
			}else if(query.getIshide()==0){
				query.setIshide(1);
				BussTask task=new BussTask();
				task.setIshide(1);
				task=bussTaskService.queryObject(task);
				if(task !=null){
					task.setIshide(0);
					bussTaskService.update(task);
				}
			}
			bussTaskService.update(query);
		}
		return AjaxResult.deleteSuccess();
	}

	/*
	 *导出
	 */
	@RequestMapping("/excel")
	public void down (BussTaskLog log) throws Exception{
		String[] headers = {"手机号码","姓名","创建时间","截图"};
		log.setCheckStatus(1);
		List<BussTaskLog> list=bussTaskLogService.queryList(log);
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow(0);
		for (short i = 0; i < headers.length; i++) {
			row.createCell(i).setCellValue(headers[i]);
		}
		String path= PropertiesUtil.getString("res.web.url");
		if(list!=null){
			for(int i=0;i<list.size();i++){
				BussTaskLog model=list.get(i);
				row = sheet.createRow(i+1);
				row.createCell(0).setCellValue(model.getPhone());
				row.createCell(1).setCellValue(model.getName());
				row.createCell(2).setCellValue(dateToString(model.getCreateDate()));
				row.createCell(3).setCellValue(path+model.getImgUpload());
			}
		}
		try {
			OutputStream out = response.getOutputStream();
			String fileName = "code.xls";// 文件名
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileName, "UTF-8"));
			workbook.write(out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 *导出
	 */
	@RequestMapping("/moban")
	public void moban () throws Exception{
		String[] headers = {"手机号码"};

		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow(0);
		for (short i = 0; i < headers.length; i++) {
			row.createCell(i).setCellValue(headers[i]);
		}
		row = sheet.createRow(1);
		row.createCell(0).setCellValue("***********");
		try {
			OutputStream out = response.getOutputStream();
			String fileName = "code.xls";// 文件名
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileName, "UTF-8"));
			workbook.write(out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void closeTask() throws Exception {
		List<BussTask> list=bussTaskService.queryClose();
		for (BussTask task: list) {
			task.setIsclose(1);
			task.setTaskStatus(0);
			bussTaskService.update(task);
		}
	}
}
